//每一对最新的一条在缓存中额外存一份
// String sessionId;// chatType为(2)时需要
// String from; //来源ID   1/2/3userid(1.s,2.t,3.p)
// String to; //目标ID	1/2/3userid(1.s,2.t,3.p)
// Long createTime; //消息创建时间long类型
// Short msgType; //消息类型int类型(0:text、1:image、2:voice、3:vedio、4:music、5:news)
// Short chatTyp; //聊天类型int类型(0:未知,1:公聊,2:私聊)
// String groupId; //群组id仅在chatType为(1)时需要,String类型
// String content; //内容
// String extras; //扩展字段,JSON对象格式如：{'扩展字段名称':'扩展字段value'}
// data = {
//	"eventType": 1实时聊天消息,2历史消息,3通知消息,4错误消息,5离线消息,6其他
// 	"sessionId": sessionId,
// 	"from": from,
// 	"to": to,
// 	"groupId": groupId,
// 	"createTime": createTime,
// 	"msgType": msgType,
// 	"chatTyp": chatTyp,
// 	"content": content,
// 	"extras": extras,
//	"isRead": 0
// }

// 分词器
// <script type="text/javascript" src="http://jimuyouyou.gitee.io/jsfenci/index.min.js"></script>
// var myDict = [
//   "家乡",
//   "松花",
//   "松花江",
//   "那里",
//   "四季",
//   "四季迷人",
//   "迷人",
//   "花香",
//   "hello",
//   "kitty",
//   "fine"
// ];
// var words = 'hello, kitty!我的家乡在松花江边上，那里有四季迷人的花香';

// var fenci = new JsFenci();
// fenci.init(myDict);
// var result = fenci.splitWords(words);
// console.log(result);

//tableName: totmsg,tosmsg,topmsg,togroupmsg
let myDB = {
	db: {},
	transaction: {},
	startTransaction(tableName) {
			//一个IDBTransacation只能使用一次
			//创建transaction有3个要求，一、有connection(数据库连接)，二、storeName(读取的store名)、三、mode(包括readonly，readwrite和versionchange)
			this.transaction = this.db.transaction([tableName], 'readwrite');
			this.transaction.oncomplete = () => console.log("transaction complete");
			this.transaction.onerror = e => console.dir(e);
	},
	initDB() {
			//下面一行代码，以数据库名(msg)和版本号(1)为参数，异步打开一个数据库
			let request = indexedDB.open('msgDB', 1);
			request.onerror = e => console.log(e.currentTarget.error.message);
			request.onsuccess = e => this.db = e.target.result;
			request.onupgradeneeded = e => {
					//如果之前数据库不存在，也会运行onupgradeneeded
					//新建objectStore
					let thisDB = e.target.result;
					if (!thisDB.objectStoreNames.contains("totmsg")) {
			// 创建数据表并设置id为自增主键
							let objStore = thisDB.createObjectStore("totmsg", {keyPath: "id",autoIncrement: true });
							//第一个参数是index名称，第二个参数是keyPath
			objStore.createIndex("sessionId", "sessionId", {unique: false});
			objStore.createIndex("createTime", "createTime", {unique: false});
					}
		if (!thisDB.objectStoreNames.contains("tosmsg")) {
			// 创建数据表并设置id为自增主键
				let objStore = thisDB.createObjectStore("tosmsg", {keyPath: "id",autoIncrement: true });
				//第一个参数是index名称，第二个参数是keyPath
			objStore.createIndex("sessionId", "sessionId", {unique: false});
			objStore.createIndex("createTime", "createTime", {unique: false});
		}
		if (!thisDB.objectStoreNames.contains("topmsg")) {
			// 创建数据表并设置id为自增主键
				let objStore = thisDB.createObjectStore("topmsg", {keyPath: "id",autoIncrement: true });
				//第一个参数是index名称，第二个参数是keyPath
			objStore.createIndex("sessionId", "sessionId", {unique: false});
			objStore.createIndex("createTime", "createTime", {unique: false});
		}
		if (!thisDB.objectStoreNames.contains("togroupmsg")) {
			// 创建数据表并设置id为自增主键
				let objStore = thisDB.createObjectStore("togroupmsg", {keyPath: "id",autoIncrement: true });
				//第一个参数是index名称，第二个参数是keyPath
			objStore.createIndex("groupId", "groupId", {unique: false});
			objStore.createIndex("createTime", "createTime", {unique: false});
		}
			};
	},
	closeDB() {
			//主动close一个connection(其实没什么意义，在被垃圾回收机制清除或创建上下文被destroy，connection会自动close)
			db.close();
	},
//添加记录
	addData(tableName, data, cb) {
			this.startTransaction(tableName);
			//Object Store是indexedDB的主要储存机制
			//IDBTransaction.objectStore()返回你查询的objectStore(IDBObjectStore对象)
			let objectStore = this.transaction.objectStore(tableName);
			let request = objectStore.add(data);
			request.onsuccess = () => {cb(true)};
			request.onerror = () => {cb(false)};
	},
//添加多条，例如获取历史消息时
addmData(tableName, mdata, cb) {
		this.startTransaction(tableName);
		let objectStore = this.transaction.objectStore(tableName);
		for (let c = 0; c < mdata.length; c++) {
			let request = objectStore.add(mdata[c]);
			request.onerror = () => {cb(false)};
			request.onsuccess = () => {cb(true)};
		}
},
//删除所有
deleteDB() {
		indexedDB.deleteDatabase('msgDB');
},
//删除某对(id为groupId或者sessionId)
deleteData(tableName, idName, id, cb) {
	this.startTransaction(tableName);
	let objectStore = this.transaction.objectStore(tableName);
	let request = objectStore.index(idName) // 索引对象
			.openCursor(IDBKeyRange.only(id));// 指针对象
	request.onsuccess = (e) => {
			let cursor = e.target.result;
			let deleteRequest;
			if (cursor) {
			deleteRequest = cursor.delete(); // 请求删除当前项
			deleteRequest.onerror = function () {
				cb(false)
			};
			deleteRequest.onsuccess = function () {
				// cb(true)
			};
			cursor.continue();
			}else{
				cb(true)
			}
	};
	request.onerror = () => {cb(false)};
},
//删除某行数据
deleteLine(tableName, idName, id, createTime, cb) {
	console.log(163, tableName, idName, id, createTime)
	this.startTransaction(tableName);
	let objectStore = this.transaction.objectStore(tableName);
	let request = objectStore.index(idName) // 索引对象
	// request.get(createTime)
		.openCursor(IDBKeyRange.only(id));// 指针对象
	request.onsuccess = (e) => {
		

			let cursor = e.target.result;
			let deleteRequest;
				
			if (cursor) {
				if(createTime==cursor.value.createTime){
					console.log(164, cursor)
					deleteRequest = cursor.delete(); // 请求删除当前项
					deleteRequest.onerror = function () {
						cb(false)
					};
					deleteRequest.onsuccess = function () {
						cb(true)
					};
				}else{
					cursor.continue();
				}
				
			}else{
				// cb('')
			}
	};
	request.onerror = () => {cb(false)};
},
//修改阅读状态（主键id）
isRead(tableName, data){
	this.startTransaction(tableName);
	let objectStore = this.transaction.objectStore(tableName);
	var index = objectStore.index('createTime');
	var request = index.get(data.createTime);
	request.onsuccess = (e) => {
		let cursor = e.target.result;
		if(cursor){
			// console.log(157, cursor,tableName, data)
			if(cursor.sessionId==data.sessionId){
				cursor.isRead = 1;
				JSON.parse(data.extras).readState = 1
				cursor.extras = data.extras
				objectStore.put(cursor);
			}else{
				cursor.continue();
			}
			
		}
		
	}
},
getDataAll(){

},
//查询(id为groupId或者sessionId)分页
getDataByPage(tableName, idName, id, page, pageSize, cb) {
	console.log(tableName, idName, id, page, pageSize)
	let rowData = [];
	let counter = 0; // 计数器
	let advanced = true; // 是否跳过多少条查询
		this.startTransaction(tableName);
		let objectStore = this.transaction.objectStore(tableName);
		let request = objectStore.index(idName) // 索引对象
		  .openCursor(IDBKeyRange.only(id), 'prev');
	request.onsuccess = (e) => {
		let cursor = e.target.result;
		if (page > 1 && advanced) {
			advanced = false;
			cursor.advance((page - 1) * pageSize); // 跳过多少条
			return;
		}
		if (cursor) {
			// 必须要检查
			rowData.unshift(cursor.value);
			counter++;
			if (counter < pageSize) {
				cursor.continue(); // 遍历了存储对象中的所有内容
			} else {
				cursor = null;
				cb(rowData);
			}
		} else {
			cb(rowData);
		}
	};
	request.onerror = () => {cb(false)};
},
	selectByNewOne(tableName, idName, id, cb) {
		this.startTransaction(tableName);
		let objectStore = this.transaction.objectStore(tableName);
		let request = objectStore.index(idName) // 索引对象
		    .openCursor(IDBKeyRange.only(id), 'prev');
		request.onsuccess = (e) => {
			let cursor = e.target.result;
			cb(cursor.value);
		};
		request.onerror = () => {cb(false)};
	},
	update(tableName,data, cb) {
		// let objectStore = this.transaction.objectStore(tableName);
		// let request = objectStore.index(idName) // 索引对象

		// .openCursor(IDBKeyRange.only(id));// 指针对象
		// request.onsuccess = (e) => {
			

		// 		let cursor = e.target.result;
		// 		// let deleteRequest;
		// 			console.log(254, tableName, idName, id, data.createTime)
		// 		if (cursor) {
		// 			if(data.createTime==cursor.value.createTime){
						
		// 				if(data.content){
		// 					cursor.extras = data.extras;
		// 				}else{
		// 					cursor.content = '';
		// 				}
		// 				console.log(164, cursor)
		// 				objectStore.put(cursor);
		// 			}else{
		// 				cursor.continue();
		// 			}
					
		// 		}else{
		// 			// cb('')
		// 		}
		// };
		// request.onerror = () => {cb(false)};
		// return
		this.startTransaction(tableName);
		let objectStore = this.transaction.objectStore(tableName);
		
		var index = objectStore.index('createTime');
		var request = index.get(data.createTime)
		request.onsuccess = (e) => {
			let cursor = e.target.result;
			if(cursor){
				console.log(221, tableName, cursor, data)
				if(data.sessionId==cursor.sessionId || data.groupId == cursor.groupId){
					if(data.delete==1){
						cursor.delete()
					}else if(data.content){
						cursor.extras = data.extras;
					}else{
						cursor.content = '';
					}
					
					objectStore.put(cursor);
				}else{
					cursor.continue();
				}
				
				
			}
			
		}
	},

}
module.exports = myDB;